package br.poli.ecomp.sma.massim.action;

import java.util.HashMap;
import java.util.Random;

import massim.monitor.Point;

import br.poli.ecomp.sma.massim.arch.EcompArch;
import jason.asSemantics.Agent;
import jason.asSemantics.DefaultInternalAction;
import jason.asSemantics.TransitionSystem;
import jason.asSemantics.Unifier;
import jason.asSyntax.Atom;
import jason.asSyntax.NumberTerm;
import jason.asSyntax.Term;

public class ChooseDirection extends DefaultInternalAction {

	static HashMap<String, Point> lastPosition = new HashMap<String,Point>();
	static HashMap<String, Integer> MoveRandom = new HashMap<String,Integer>();
	static int count = 0;
	
	@Override
	public Object execute(TransitionSystem ts, Unifier un, Term[] args)
			throws Exception {
		
		Term x = args[0];
		Term y = args[1];
		Term direction = args[2];
		
		double vx = ((NumberTerm)x).solve();
		double vy = ((NumberTerm)y).solve();
		
		EcompArch agent =  (EcompArch) ts.getUserAgArch();
		String agentName = agent.getAgName();
		String orientation = "north";
		
		Point position = new Point((int)vx,(int)vy);
		Point oldPosition = lastPosition.get(agentName);
		
		if (oldPosition != null){
			
			if (((int)vx == oldPosition.x) && ((int)vy == oldPosition.y)){
				MoveRandom.put(agentName, 1);
			}
		}
		
		lastPosition.put(agentName, position);		
		
		Integer flag = MoveRandom.get(agentName);
		Random random = new Random();
		
		if (flag != null && flag == 1){
		
			orientation = new String [] {"north","south","west","east","northeast","southeast","southwest","northwest"}[random.nextInt(8)];
			MoveRandom.put(agentName, new Integer(0));
		}else{
				
			orientation = "north";
			
		}
		
		un.unifies(direction, new Atom(orientation));
		System.out.println("Nome do agente: " +  agent.getAgName() + " Orientation: " + orientation);
		return true;
	}

}
